package com.springsource.mvc.HandlerMappingAndHandlerAdapter;

import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

public class HandlerMappingAndHandlerAdapter {
    public static void main(String[] args) throws Exception {
        AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(WebConfig.class);
        // 解析@RequestMapping及其派生注解，生成路径与控制器方法之间的映射关系，在初始化时生成
        RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
        // 获取映射结果
//        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
//        handlerMethods.forEach((requestMappingInfo, handlerMethod) -> {
//            System.out.println("requestMappingInfo: " + requestMappingInfo);
//            System.out.println("handlerMethod: " + handlerMethod);
//        });
        // 通过请求获取控制器方法信息
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        request.setMethod("PUT");
        request.setRequestURI("/test4.yml");
        request.setParameter("name", "张三");
        request.addHeader("token", "123");
        HandlerExecutionChain handler = handlerMapping.getHandler(request);
//        System.out.println("handler: " + handler);

        // 控制器方法调用
        MyRequestMappingHandlerAdapter handlerAdapter = (MyRequestMappingHandlerAdapter)context.getBean("requestMappingHandlerAdapter");
        handlerAdapter.invokeHandlerMethod(request, response, (HandlerMethod)handler.getHandler());
        String contentAsString = response.getContentAsString();
        System.out.println("contentAsString: " + contentAsString);

        // 参数解析器
//        handlerAdapter.getArgumentResolvers().forEach(System.out::println);
        // 返回值解析器
//        handlerAdapter.getReturnValueHandlers().forEach(System.out::println);

    }
}
